package com.cangshi.controller;

import com.alibaba.fastjson.JSON;
import com.cangshi.entity.*;
import com.cangshi.service.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * Created by Eoly on 2016/12/22.
 */

@Controller
public class OrderController {

    @Autowired
    GroupService groupService;

    @Autowired
    UserService userService;

    @Autowired
    BillService billService;

    @Autowired
    OrderService orderService;

    @Autowired
    AddressService addressService;

    @Autowired
    GroupUserService groupUserService;

    private static final Logger LOGGER = Logger.getLogger(OrderController.class);

    /**
     * 获取用户订单列表
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/order/show-user-orders", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public JsonObject findUserOrder(HttpServletRequest request) {
        JsonObject<Order> jsonObject = new JsonObject<Order>();
        //获得用户
        UserBaseInfo userLogin = (UserBaseInfo) request.getAttribute("user");

        List<Order> orderList = orderService.findByUserId(userLogin.getUserId());
        if (orderList.isEmpty()) {
            jsonObject.setError(761);
            jsonObject.setMes("该用户没有任何订单");
            return jsonObject;
        }
        jsonObject.setError(0);
        jsonObject.setMes("获取成功，共" + orderList.size() + "条订单信息");
        jsonObject.setDataList(orderList);
        return jsonObject;
    }

    /**
     * 获取商家订单列表
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/order/show-seller-orders", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public JsonObject findOrderUserOrder(HttpServletRequest request) {
        JsonObject<Order> jsonObject = new JsonObject<Order>();
        //获得用户
        UserBaseInfo userLogin = (UserBaseInfo) request.getAttribute("user");

        List<Order> orderList = orderService.findByOrderUserId(userLogin.getUserId());
        if (orderList.isEmpty()) {
            jsonObject.setError(761);
            jsonObject.setMes("该商家没有任何订单");
            return jsonObject;
        }
        jsonObject.setError(0);
        jsonObject.setMes("获取成功，共" + orderList.size() + "条订单信息");
        jsonObject.setDataList(orderList);
        return jsonObject;
    }

    /**
     * 订单付款功能
     *
     * @param orderId
     * @param payPsw
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/order/pay", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public JsonObject payOrder(@RequestParam(required = false) Integer orderId, @RequestParam(required = false) String payPsw, HttpServletRequest request) {
        JsonObject jsonObject = new JsonObject();

        //获得用户
        UserBaseInfo userLogin = (UserBaseInfo) request.getAttribute("user");

        //检查完整性
        if (orderId == null || payPsw == null) {

            jsonObject.setError(731);
            jsonObject.setMes("参数不完整:请求需要订单id、支付密码");
            return jsonObject;
        }

        //获取用户信息
        User checkUser = userService.getUserById(userLogin.getUserId());

        //获取订单信息
        Order preOrder = orderService.findByOrderId(orderId);
        if (preOrder == null) {
            jsonObject.setError(732);
            jsonObject.setMes("暂时没有找到订单id为:" + orderId + "，请稍候再试");
            return jsonObject;
        }

        //验证订单信息是否和用户信息匹配
        if (!checkUser.getUserId().equals(preOrder.getUserId())) {
            jsonObject.setError(752);
            jsonObject.setMes("该订单不是该用户的订单");
            return jsonObject;
        }


        //核对订单是否为未付款
        if (preOrder.getOrderStatus() != 0) {
            jsonObject.setError(754);
            jsonObject.setMes("该订单无法付款，请检查订单状态");
            return jsonObject;
        }

        //获取欲参加的团
        Group preGroup = groupService.findGroupByGroupId(preOrder.getGroupId());
        if (preGroup == null) {

            jsonObject.setError(755);
            jsonObject.setMes("该订单不是一个有效的订单");
            return jsonObject;
        }

        //获取团状态
        if (preGroup.getGroupStatus() != 0) {

            jsonObject.setError(756);
            jsonObject.setMes("该订单所绑定团已无法参团");

            //修改订单信息
            preOrder.setOrderStatus(-1);
            orderService.modifyOrder(preOrder);

            return jsonObject;
        }

        //检查团预支和订单金额是否一致
        if (preOrder.getOrderMoney() != (preGroup.getGroupPrice() + preGroup.getGroupPostage())) {

            jsonObject.setError(753);
            jsonObject.setMes("该订单绑定的团信息发生变化，该订单已失效");

            //修改订单信息
            preOrder.setOrderStatus(-1);
            orderService.modifyOrder(preOrder);

            return jsonObject;
        }

        //判断用户是否已参团
        GroupUserKey checkGroupUser = new GroupUserKey();
        checkGroupUser.setGroupId(preGroup.getGroupId());
        List<GroupUserKey> groupUserKeyList = groupUserService.findIdByRequestId(checkGroupUser);
        if (!groupUserKeyList.isEmpty()) {
            for (GroupUserKey groupUserKey : groupUserKeyList) {
                //判断用户是否参团
                if (userLogin.getUserId().equals(groupUserKey.getUserId())) {
                    jsonObject.setError(736);
                    jsonObject.setMes("该订单已失效,该用户已经参加此团");

                    //修改订单信息
                    preOrder.setOrderStatus(-1);
                    orderService.modifyOrder(preOrder);
                    return jsonObject;
                }
            }
        }

        //判断团参加人数是否超标
        if (preGroup.getGroupTargetNumber() <= groupUserKeyList.size()) {

            jsonObject.setError(735);
            jsonObject.setMes("该订单已失效,参团人数已达上限");
            //修改订单信息
            preOrder.setOrderStatus(-1);
            orderService.modifyOrder(preOrder);
            return jsonObject;
        }

        //验证支付密码
        if (!payPsw.equals(checkUser.getUserPayPsw())) {

            jsonObject.setError(733);
            jsonObject.setMes("支付密码输入错误");
            return jsonObject;
        }

        //创建账单
        Bill bill = new Bill();
        bill.setUserId(userLogin.getUserId());
        bill.setBillChangeValue(preGroup.getGroupPrice() + preGroup.getGroupPostage());
        bill.setBillChangeType(-1);
        bill.setBillOrigin("参团商品预支");
        bill.setBillInfo("参团id:" + preGroup.getGroupId() + ",商品价格：￥" + preGroup.getGroupPrice() + ",邮费：￥" + preGroup.getGroupPostage());
        //获取账单生成结果
        Integer resultForBill = billService.addBill(bill);

        //700：用户余额不足
        if (resultForBill == 700) {
            jsonObject.setError(resultForBill);
            jsonObject.setMes("用户余额不足");
            return jsonObject;
        }


        //绑定用户到团-用户列表
        GroupUserKey groupUserKey = new GroupUserKey();
        groupUserKey.setUserId(preOrder.getUserId());
        groupUserKey.setGroupId(preGroup.getGroupId());
        Integer resultForGroupUser = groupUserService.addUserGroup(groupUserKey);

        //参团失败
        if (resultForGroupUser != 1) {
            bill.setBillChangeType(1);
            bill.setBillOrigin("参团失败退款");
            resultForBill = billService.addBill(bill);
            if (resultForBill != 1) {
                jsonObject.setError(-101);
                jsonObject.setMes("参团失败，退款失败，请联系客服");
                return jsonObject;
            }
            jsonObject.setError(733);
            jsonObject.setMes("参团失败，已成功退款");
            return jsonObject;
        }

        //修改订单状态
        preOrder.setOrderStatus(1);
        orderService.modifyOrder(preOrder);

        //获取参团后团人数
        GroupUserKey groupUserCheck = new GroupUserKey();
        groupUserCheck.setGroupId(preGroup.getGroupId());
        Integer groupNowNumber = groupUserService.getTheNumberGroupJoinedOrUserOwned(groupUserCheck);

        //若未获取人数失败
        if (groupNowNumber != null) {

            //更新人数
            Group resultGroup = new Group();
            resultGroup.setGroupId(preGroup.getGroupId());
            resultGroup.setGroupNowNumber(groupNowNumber);

            //若团人数刚好满
            if (groupNowNumber.equals(preGroup.getGroupTargetNumber())) {

                //修改团状态
                resultGroup.setGroupStatus(1);

                //获得团所有订单
                List<Order> orders = orderService.findByGroupId(preGroup.getGroupId());

                //修改订单状态
                for (Order eachOrder : orders) {

                    //剔除订单状态不是付款成功的
                    if (eachOrder.getOrderStatus() != 1) {
                        continue;
                    }

                    Order checkOrder = new Order();
                    checkOrder.setOrderId(eachOrder.getOrderId());
                    checkOrder.setOrderStatus(2);
                    //提交修改
                    orderService.modifyOrder(checkOrder);
                }

            }
            groupService.updateGroup(resultGroup);
            jsonObject.setMes("付款成功，参团成功");
        } else {
            jsonObject.setMes("付款成功，参团成功,更新参团人数失败");
        }

        jsonObject.setError(0);


        //返回结果
        return jsonObject;
    }

    /**
     * 获取订单详细信息
     *
     * @param orderId
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/order/find-order-deeply", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public JsonObject findOrderDeeply(@RequestParam(required = false) Integer orderId, HttpServletRequest request) {
        JsonObject<Order> jsonObject = new JsonObject<Order>();
        //获得用户
        UserBaseInfo userLogin = (UserBaseInfo) request.getAttribute("user");

        //检查完整性
        if (orderId == null) {

            jsonObject.setError(731);
            jsonObject.setMes("参数不完整:请求需要订单id");
            return jsonObject;
        }

        //获取订单详情
        Order order = orderService.findByOrderIdDeeply(orderId);
        if (order == null) {

            jsonObject.setError(741);
            jsonObject.setMes("没有找到该订单");
            return jsonObject;
        }

        //核对登录用户是否匹配
        if (!order.getUserId().equals(userLogin.getUserId())) {

            if (order.getOrderUserId().equals(userLogin.getUserId())) {

                jsonObject.setError(1);
                jsonObject.setData(order);
                jsonObject.setMes("获取成功,该订单为商家订单");
                return jsonObject;
            }

            jsonObject.setError(742);
            jsonObject.setMes("该用户订单列表没有该订单");
            return jsonObject;
        }

        jsonObject.setData(order);
        jsonObject.setMes("获取成功,该订单为用户订单");
        jsonObject.setError(0);


        //返回结果
        return jsonObject;
    }


    /**
     * 获取某个团的所有订单
     *
     * @param request
     * @param groupId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/order/show-group-orders", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public JsonObject findGroupOrder(HttpServletRequest request, @RequestParam(required = false) Integer groupId) {
        JsonObject<Order> jsonObject = new JsonObject<Order>();

        //获得用户
        UserBaseInfo userLogin = (UserBaseInfo) request.getAttribute("user");

        if (groupId == null) {
            jsonObject.setError(731);
            jsonObject.setMes("请求参数不完整，缺少团id");
            return jsonObject;
        }

        //获取团信息
        Group checkGroup = groupService.findGroupByGroupId(groupId);
        if (checkGroup == null) {
            jsonObject.setError(751);
            jsonObject.setMes("获取团信息失败，请检查团id是否正确");
            return jsonObject;
        }

        if (!checkGroup.getGroupInitiatorId().equals(userLogin.getUserId())) {
            jsonObject.setError(752);
            jsonObject.setMes("该用户不是该团的发起者，无法查看该团订单");
            return jsonObject;
        }

        List<Order> orderList = orderService.findByGroupId(checkGroup.getGroupId());
        if (orderList.isEmpty()) {
            jsonObject.setError(781);
            jsonObject.setMes("该团没有任何订单");
            return jsonObject;
        }

        jsonObject.setDataList(orderList);
        jsonObject.setMes("获取成功，团id为" + groupId + "的团共有订单" + orderList.size() + "条");
        jsonObject.setError(0);


        //返回结果
        return jsonObject;
    }

    /**
     * 发货功能
     *
     * @param request
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/order/order-sent-out", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public JsonObject orderSentOut(HttpServletRequest request, @RequestParam(required = false) Integer orderId) {
        JsonObject jsonObject = new JsonObject();

        //获得用户
        UserBaseInfo userLogin = (UserBaseInfo) request.getAttribute("user");

        if (orderId == null) {
            jsonObject.setError(731);
            jsonObject.setMes("请求参数不完整，缺少订单id");
            return jsonObject;
        }

        Order checkOrder = orderService.findByOrderId(orderId);

        if (checkOrder == null) {
            jsonObject.setError(751);
            jsonObject.setMes("获取订单信息失败，请检查订单id是否正确");
            return jsonObject;
        }

        if (!checkOrder.getOrderUserId().equals(userLogin.getUserId())) {
            jsonObject.setError(752);
            jsonObject.setMes("该用户不是该订单的商家，无法执行该请求");
            return jsonObject;
        }

        if (checkOrder.getOrderStatus() != 2) {
            jsonObject.setError(753);
            jsonObject.setMes("该订单目前不能发货");
            return jsonObject;
        }

        //修改订单状态
        Order resultOrder = new Order();
        resultOrder.setOrderStatus(3);
        resultOrder.setOrderId(orderId);

        if (orderService.modifyOrder(resultOrder) != 1) {
            jsonObject.setError(754);
            jsonObject.setMes("发货失败，请重试");
            return jsonObject;
        }

        jsonObject.setError(0);
        jsonObject.setMes("发货成功");

        //返回结果
        return jsonObject;
    }


    /**
     * 确认收货功能
     *
     * @param request
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/order/order-received", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public JsonObject orderReceived(HttpServletRequest request, @RequestParam(required = false) Integer orderId) {
        JsonObject jsonObject = new JsonObject();

        //获得用户
        UserBaseInfo userLogin = (UserBaseInfo) request.getAttribute("user");

        if (orderId == null) {
            jsonObject.setError(731);
            jsonObject.setMes("请求参数不完整，缺少订单id");
            return jsonObject;
        }

        Order checkOrder = orderService.findByOrderId(orderId);

        if (checkOrder == null) {
            jsonObject.setError(751);
            jsonObject.setMes("获取订单信息失败，请检查订单id是否正确");
            return jsonObject;
        }

        if (!checkOrder.getUserId().equals(userLogin.getUserId())) {
            jsonObject.setError(752);
            jsonObject.setMes("该用户不拥有该订单，无法执行该请求");
            return jsonObject;
        }

        if (checkOrder.getOrderStatus() != 3) {
            jsonObject.setError(753);
            jsonObject.setMes("该订单目前不能确认收货");
            return jsonObject;
        }

        //修改订单状态
        Order resultOrder = new Order();
        resultOrder.setOrderStatus(4);
        resultOrder.setOrderId(orderId);
        resultOrder.setOrderEndTime(new Date(System.currentTimeMillis()));

        if (orderService.modifyOrder(resultOrder) != 1) {
            jsonObject.setError(754);
            jsonObject.setMes("确认收货失败，请重试");
            return jsonObject;
        }

        //创建账单
        Bill bill = new Bill();
        bill.setUserId(checkOrder.getOrderUserId());
        bill.setBillChangeValue(checkOrder.getOrderMoney());
        bill.setBillChangeType(1);
        bill.setBillOrigin("团购商品销售成功");
        bill.setBillInfo("商品团id:" + checkOrder.getGroupId() + ",订单id：" + checkOrder.getOrderId() + ",订单价格：￥" + checkOrder.getOrderMoney());

        billService.addBill(bill);


        jsonObject.setError(0);
        jsonObject.setMes("确认收货成功");


        //返回结果
        return jsonObject;
    }

}
